package com.xjmall.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.xjmall.common.Const;
import com.xjmall.common.ServerResponse;
import com.xjmall.common.ServerResult;
import com.xjmall.dao.CategoryMapper;
import com.xjmall.exception.DataNotFoundException;
import com.xjmall.exception.ParameterCheckException;
import com.xjmall.pojo.Category;
import com.xjmall.service.ICategoryService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 商品分类管理业务接口的实现类
 * Created by An on 2017/5/7.
 */
@Service("iCategoryService")
public class CategoryServiceImpl implements ICategoryService {

    private static Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 添加商品分类信息
     * @param category 待添加的商品分类信息
     * @return ServerResult
     */
    @Override
    public ServerResult addCategory(Category category) {
        // 如果parentid为null，则设置默认值
        if (category.getParentId() == null) {
            category.setParentId(0);
        }
        // 校验分类名称，排序权重，层级和图片url
        if (category.getName() == null || category.getName() == "") {
            throw new ParameterCheckException("商品分类名称不能为空");
        }
        if (category.getSortOrder() == null) {
            throw new ParameterCheckException("商品分类的排序权重不能为空");
        }
        if (category.getDeep() > 4) {
            throw new ParameterCheckException("商品分类层级最多为四层");
        }
        if (category.getUrl() == null || category.getUrl() == "") {
            throw new ParameterCheckException("商品分类图片不能为空");
        }
        category.setStatus(Const.CategoryStatus.CATEGORY_USE); // 设置分类的状态为可用
        int rowCount = categoryMapper.insertSelective(category);
        if (rowCount < 1) {
            throw new DataNotFoundException("添加品类失败");
        }
        return ServerResult.successMsg("添加品类成功");
    }

    /**
     * 更新商品分类信息
     * @param id 分类id
     * @param name 分类名称
     * @param url 分类图片url
     * @return ServerResult
     */
    @Override
    public ServerResult updateCategory(Integer id, String name, String url) {
        // 校验id，name, url
        if (id == null) {
            throw new ParameterCheckException("商品分类id不能为空");
        }
        if (name.equals("") || name == null) {
            throw new ParameterCheckException("商品分类名称不能为空");
        }
        if (url.equals("") || url == null) {
            throw new ParameterCheckException("商品分类图片不能为空");
        }
        Category category = new Category();
        category.setId(id);
        category.setName(name);
        category.setUrl(url);
        int resultCount = categoryMapper.updateByPrimaryKeySelective(category);
        if (resultCount < 1) {
            throw new DataNotFoundException("修改品类失败");
        }
        return ServerResult.successMsg("修改品类成功");
    }

    /**
     * 根据分类id查询分类信息
     * @param id 分类id
     * @return ServerResult
     */
    @Override
    public ServerResult getCategoryById(Integer id) {
        Category category = categoryMapper.selectByPrimaryKey(id);
        return ServerResult.successData(category);
    }

    /**
     * 根据分类的父id查询分类列表
     * @param parentId 分类父id
     * @return ServerResult
     */
    @Override
    public ServerResult getChildrenParallelCategory(Integer parentId) {
        List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(parentId);
        if (CollectionUtils.isEmpty(categoryList)) {
            throw new DataNotFoundException("当前分类下没有子分类");
        }
        return ServerResult.successData(categoryList);
    }

    /**
     * 根据分类id批量删除分类信息
     * @param delIds 分类id
     * @return ServerResult
     */
    @Override
    public ServerResult deleteCategoryByIds(String delIds) {
        if (delIds == null || delIds.equals("")) {
            throw new ParameterCheckException("分类id不能为空");
        }
        String[] delIdsArray = delIds.split(",");
        for (String delId : delIdsArray) {
            Integer id = Integer.parseInt(delId);
            int rowCount = categoryMapper.deleteByPrimaryKey(id);
            if (rowCount < 1) {
                throw new DataNotFoundException("id为" + delId + "的分类信息删除失败，终止删除");
            }
        }
        return ServerResult.successMsg("分类信息删除成功");
    }

    /**
     * 根据分类id修改分类状态
     * @param id 分类id
     * @param status 分类状态
     * @return ServerResult
     */
    @Override
    public ServerResult updateCategoryStatusById(Integer id, Integer status) {
        // 校验分类状态有效性
        if (status != 0 || status != 1) {
            throw new ParameterCheckException("非法参数");
        }
        Category category = new Category();
        category.setId(id);
        category.setStatus(status);
        int rowCount = categoryMapper.updateByPrimaryKeySelective(category);
        if (rowCount < 1) {
            throw new DataNotFoundException("修改失败");
        }
        return ServerResult.successMsg("修改成功");
    }

    @Override
    public ServerResponse<List<Integer>> selectCategoryAndChildrenById(Integer categoryId) {
        Set<Category> categorySet = Sets.newHashSet();
        List<Integer> categoryIdList = Lists.newArrayList();
        findChildrenCategory(categorySet, categoryId);
        if (categoryId != null) {
            for (Category categoryItem : categorySet) {
                categoryIdList.add(categoryItem.getId());
            }
        }
        return ServerResponse.createBySuccess(categoryIdList);
    }

    @Override
    public ServerResponse<List<Category>> getMCategories() {
        List<Category> allLists = categoryMapper.selectAllWithoutDeleted();
        List<Category> resultList = Lists.newArrayList();
        for (Category category : allLists) {
            if (category.getParentId() == 0) {
                resultList.add(category);
            }
        }
        for (Category category : resultList) {
            List<Category> childList = subLists(category.getId(), allLists);
            if (childList.size() > 0) {
                for (Category c : childList) {
                    List<Category> children = subLists(c.getId(), allLists);
                    if (children.size() > 0) {
                        c.setChildren(children);
                    }
                }
            }
            category.setChildren(childList);
        }
        return ServerResponse.createBySuccess(resultList);
    }

    private List<Category> subLists(Integer parentId, List<Category> allLists) {
        List<Category> resultList = Lists.newArrayList();
        for (Category category : allLists) {
            if (parentId.equals(category.getParentId()) && !category.getDeep().equals(1)) {
                resultList.add(category);
            }
        }
        return resultList;
    }

    /**
     * 递归查询子节点
     * @param categorySet
     * @param categoryId
     * @return
     */
    private Set<Category> findChildrenCategory(Set<Category> categorySet, Integer categoryId) {
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if (category != null) {
            categorySet.add(category);
        }
        List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId);
        for (Category categoryItem : categoryList) {
            findChildrenCategory(categorySet, categoryItem.getId());
        }
        return categorySet;
    }
}
